/*
 * CN_READY.cpp
 *
 *  Created on: 2013. 12. 7.
 *      Author: mega
 */

#include "../../Command.h"
#include "../../User.h"

#include "../../NLogic/Space.h"
#include "../../NLogic/Party.h"
#include "../../NLogic/Battle.h"
#include "../../NLogic/Function.h"

namespace ProjectZ { namespace NCommand {

void readyPracticeMatch(User * pUser, int hp, int sp)
{
	pUser->GetBattle()->GetData().HP = hp;
	pUser->GetBattle()->GetData().HP_MAX = hp;
	pUser->GetBattle()->GetData().SP = sp;
	pUser->GetBattle()->GetData().SP_MAX = sp;
	pUser->GetBattle()->GetData().bReadyFight = true;

	::Network::Packet * pNoti = ::Network::GETPACKETPOOL()->SEND_NEW();
	pNoti->MakePacket(CMD_SN_FIGHT);
	pUser->Send(pNoti);
}


void Command::CN_READY(User * pUser, ::Network::Packet * pPacket)
{
	PREPARE_PACKET;

	NLogic::Space * pSpace = pUser->GetSpace();
	if (pSpace == NULL)
	{
		DEBUGLOG("CN_READY : pSpace is NULL!!");
		return;
	}

	uint32_t hp	= 0;
	uint32_t sp = 0;

	*pPacket >> hp >> sp;

	// AI 대전인 경우
	if (pSpace->GetData()._spaceType == NLogic::Space::SpaceType::PVP_PRACTICE)
	{
		readyPracticeMatch(pUser, hp, sp);
		return;
	}

	NLogic::Party * pParty = pSpace->GetParty();
	if (NULL == pParty)
	{
		DEBUGLOG("CN_READY : pParty is NULL!!");
		return;
	}

	// PVP 전투중에 입장하는 경우에는 이미 AI가 수행중이므로
	// 여기서 HP를 설정하면 안된다
	if (pParty->GetState() == NLogic::Party::State::PVP_BATTLE)
	{
		// do nothing..
	}
	else
	{
		pUser->GetBattle()->GetData().userseq = pUser->GetUserSeq();
		pUser->GetBattle()->GetData().HP = hp;
		pUser->GetBattle()->GetData().HP_MAX = hp;
		pUser->GetBattle()->GetData().SP = sp;
		pUser->GetBattle()->GetData().SP_MAX = sp;
		pUser->GetBattle()->GetData().bReadyFight = true;
	}

	User * pOppUser = pUser->GetBattle()->GetData()._pvpOppUser;

	if (NULL == pOppUser)
	{
		DEBUGLOG("CN_READY : pOppUser is NULL!!!");
		return;
	}

	if (false == pOppUser->GetBattle()->GetData().bReadyFight)
		return;

	::Network::Packet * pNoti = ::Network::GETPACKETPOOL()->SEND_NEW();
	pNoti->MakePacket(CMD_SN_FIGHT);
	pUser->Send(pNoti);

	pUser->SetEnumState(User::EnumState::PVP_BATTLE);

	if (NULL != pOppUser)
	{
		// 상대가 전투중이라면 패킷을 보내지 않는다
		if (pOppUser->GetEnumState() == User::EnumState::PVP_BATTLE)
		{
			// do nothing..
		}
		else
		{
			::Network::Packet * pNoti = ::Network::GETPACKETPOOL()->SEND_NEW();
			pNoti->MakePacket(CMD_SN_FIGHT);
			pOppUser->Send(pNoti);
		}
	}

	pSpace->GetData()._starttick	= NLogic::NFunction::GetTickCount();
	pSpace->GetData()._finishtick	= 0;

	// Party 상태 변경
	if (pParty->GetState() == NLogic::Party::State::PVP_READY_WAIT)
	{
		pParty->SetState(NLogic::Party::State::PVP_BATTLE);
	}
}

} /*NCommand*/ } /*ProjectZ*/

